package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.SystemFriendLinkManager;
import com.fish.anne.model.SystemFriendLink;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class SystemFriendLinkAction extends BaseAction implements Preparable {
    private SystemFriendLinkManager systemFriendLinkManager;
    private List systemFriendLinks;
    private SystemFriendLink systemFriendLink;
    private Long  linkId;

    public void setSystemFriendLinkManager(SystemFriendLinkManager systemFriendLinkManager) {
        this.systemFriendLinkManager = systemFriendLinkManager;
    }

    public List getSystemFriendLinks() {
        return systemFriendLinks;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String systemFriendLinkId = getRequest().getParameter("systemFriendLink.linkId");
            if (systemFriendLinkId != null && !systemFriendLinkId.equals("")) {
                systemFriendLink = systemFriendLinkManager.get(new Long(systemFriendLinkId));
            }
        }
    }

    public String list() {
        systemFriendLinks = systemFriendLinkManager.getAll();
        return SUCCESS;
    }

    public void setLinkId(Long  linkId) {
        this. linkId =  linkId;
    }

    public SystemFriendLink getSystemFriendLink() {
        return systemFriendLink;
    }

    public void setSystemFriendLink(SystemFriendLink systemFriendLink) {
        this.systemFriendLink = systemFriendLink;
    }

    public String delete() {
        systemFriendLinkManager.remove(systemFriendLink.getLinkId());
        saveMessage(getText("systemFriendLink.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (linkId != null) {
            systemFriendLink = systemFriendLinkManager.get(linkId);
        } else {
            systemFriendLink = new SystemFriendLink();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (systemFriendLink.getLinkId() == null);

        systemFriendLinkManager.save(systemFriendLink);

        String key = (isNew) ? "systemFriendLink.added" : "systemFriendLink.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}